/**
 * 宠币充值配置组件
 * 用于配置宠币充值活动的门槛、赠送比例和促销文案等信息
 */
import React, { Component } from 'react';
import { Checkbox, Form, Input, InputNumber, message, Modal, Radio, Select, Space, Switch } from "antd";
import TheButton from "@/components/TheButton";
import { rechargeWithdrawList, apiGetDetailByType, apiUpdateCapitalConfig } from '@/request/wallet/rechargeWithdraw'

class SalesPromotion extends Component {
    /**
     * 组件构造函数
     * 初始化组件状态，包括开关状态、模态框可见性等
     */
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            withdrawalServiceFeeFake: 0,//体现服务费划线
            withdrawalServiceFee: 0,//提现服务费
            salesPromotionConfig: {},
            loading: false
        }
    }


    componentDidMount() {
        this.getData()
    }

    getData = () => {
        apiGetDetailByType({ dataType: 'TX' }).then(res => {
            if (res.code == 0 && res.data) {
                this.setState({
                    salesPromotionConfig: res.data,
                    switchValue: res.data.configState == 'Y'
                })
            }
        })
    }


    switchChange = async (e) => {
        if (e) {
            // 开启时需要弹出模态框确认保存
            // this.setState({
            //     visible: true,
            // })
            this.setState({
                switchLoading: true
            }, () => {
                this.openModal()
            })
        } else {
            this.setState({
                switchLoading: true
            }, () => {
                apiUpdateCapitalConfig({ configId: this.state.salesPromotionConfig.configId, configState: 'N', dataType: 'TX' }).then(res => {
                    React.$message({ type: 'success', content: '促销关闭' })
                    this.setState({
                        switchLoading: false
                    }, () => {
                        this.getData()
                    })
                }).catch(err => {
                    this.setState({
                        switchLoading: false
                    }, () => {
                        this.getData()
                    })
                })
            })

        }
    }

    /**
     * 打开模态框
     * 设置模态框为可见，并根据当前的配置数据设置表单的默认值
     */
    openModal = () => {
        rechargeWithdrawList({ type: 0 }).then(res => {
            if (res.code === 0 && res.data) {
                this.setState({
                    withdrawalServiceFeeFake: res.data.withdrawalServiceFeeFake,//划线提现服务费
                    withdrawalServiceFee: res.data.withdrawalServiceFee,//提现服务费
                }, () => {
                    let config = this.state.salesPromotionConfig
                    this.setState({ visible: true }, () => {
                        this.formRef.current.setFieldsValue({
                            userRange: config.pickType == "ALL" ? 'ALL' : "NOALL",
                            promotionServicePrice: config.priceRatioByAll/100,
                            promotionTxt: config.promotionOfficialByAll,
                            sights: [
                                {
                                    label: '新用户',
                                    value: 'NEW',
                                    userMode: ['NEW'],
                                    definition: [1, 2].includes(config.definitionPickByNew) ? config.definitionPickByNew : null,
                                    registerDay: config.registerDaysByNew,
                                    payoutCount: config.limitNumberByNew,
                                    promotionServicePrice: config.priceRatioByNew / 100,
                                    promotionTxt: config.promotionOfficialByNew,
                                },
                                {
                                    label: '其他用户', value: 'ANOTHER',
                                    userMode: config.pickType == "ANOTHER" ? ['ANOTHER'] : null,
                                    promotionTxt: config.promotionOfficialByAnother,
                                    promotionServicePrice: config.priceRatioByAnother / 100

                                }
                            ]



                        })
                    })

                })
            }
        })


    }

    /**
     * 关闭模态框
     * 重置模态框可见性和表单数据
     */
    closeModal = () => {
        this.setState({
            visible: false,
            switchLoading: false
        })
        this.formRef.current.resetFields()
    }
    /**
     * 表单提交的处理函数
     * 验证表单数据并根据验证结果执行保存操作
     * @param values 表单提交的值
     */
    onFinish = async (values) => {
        await this.formRef.current.validateFields().then(async (values) => {
            console.log(values)
            try {
                this.setState({
                    loading: true
                })
                const { userRange, promotionTxt, promotionServicePrice, sights } = values
                let params = {
                    dataType: 'TX',
                    configId: this.state.salesPromotionConfig.configId,
                    configState: 'Y'
                }
                if (userRange == "ALL") {
                    params = {
                        ...params,

                        dataType: 'TX',
                        pickType: 'ALL',
                        priceRatioByAll: promotionServicePrice * 100,
                        promotionOfficialByAll: promotionTxt
                    }
                } else {
                    if (sights[1].userMode && sights[1].userMode[0] == 'ANOTHER') {

                        params = {
                            ...params,

                            dataType: 'TX',
                            pickType: 'ANOTHER',
                            promotionOfficialByAnother: sights[1].promotionTxt,
                            priceRatioByAnother: sights[1].promotionServicePrice * 100,
                            promotionOfficialByNew: sights[0].promotionTxt,
                            priceRatioByNew: sights[0].promotionServicePrice * 100,
                            definitionPickByNew: sights[0].definition,
                        }
                        if (sights[0].definition == 1) {
                            params.registerDaysByNew = sights[0].registerDay
                        } else {
                            params.limitNumberByNew = sights[0].payoutCount
                        }
                    } else {
                        params = {
                            ...params,
                            dataType: 'TX',
                            pickType: 'NEW',
                            promotionOfficialByNew: sights[0].promotionTxt,
                            priceRatioByNew: sights[0].promotionServicePrice * 100,
                            definitionPickByNew: sights[0].definition
                        }
                        if (sights[0].definition == 1) {
                            params.registerDaysByNew = sights[0].registerDay
                        } else {
                            params.limitNumberByNew = sights[0].payoutCount
                        }
                    }
                }

                apiUpdateCapitalConfig(params).then(res => {
                    if (res.code == 0) {
                        React.$message({ type: 'success', content: '保存成功' })
                        this.setState({
                            visible: false,
                            loading: false,
                            switchLoading: false

                        }, () => {
                            this.getData()
                        })

                    }
                }).catch(err => {
                    this.setState({
                        loading: false,
                        switchLoading: false
                    })
                })
            } catch (error) {
                this.setState({
                    loading: false,
                    switchLoading: false
                })
            }

        })
    }
    // 获取服务费和文案dom
    getServicePriceAndTip = (labelCol, field) => {
        return <div>
            <Form.Item label="优惠后的提现服务费" required={true}
                labelCol={{
                    span: labelCol,
                }}

            >
                <Form.Item
                    name={field ? [field.name, 'promotionServicePrice'] : 'promotionServicePrice'}
                    fieldKey={field ? [field.fieldKey, 'promotionServicePrice'] : ''}
                    noStyle
                    rules={[
                        {
                            required: true,
                            pattern: /^-?[0-9]\d*$/,
                            message: `请输入整数类型`,
                        },
                        {
                            type: 'number',
                            min: 0,
                            max: this.state.withdrawalServiceFee,
                            message: `请输入0~${this.state.withdrawalServiceFee}范围内的整数!`,
                        }
                    ]}
                >
                    <InputNumber style={{ width: 120 }} min={0} max={30} />
                </Form.Item>
                <span className="ant-form-text">%</span>
            </Form.Item>
            <Form.Item
                label="促销文案"
                name={field ? [field.name, 'promotionTxt'] : 'promotionTxt'}
                fieldKey={field ? [field.fieldKey, 'promotionTxt'] : ''}
                labelCol={{
                    span: labelCol
                }}
                wrapperCol={{
                    span: 24 - labelCol
                }}
            >
                <Input style={{ width: 200 }} maxLength={20} showCount />
            </Form.Item>
        </div>
    }
    onInput = (e) => {
        let value = e.target.value
        e.target.value = this.regInput(value)
    }
    regInput(value) {
        value = value.replace(/[^\d.]/g, '')// 只能是数字和小数点，不能是其他输入
        value = value.replace(/^\./g, "");// 保证第一位只能是数字，不能是点
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");  // 小数只能出现1位
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 小数点后面保留2位
        return value
    }
    onValuesChange = (value, allValue) => {
        // 根据特定字段的值变化重置其他字段
        console.log(value, allValue);
        if (value.userRange == 'NOALL') {
            this.formRef.current.setFieldsValue({
                sights: [{
                    label: '新用户', value: 'NEW',
                    registerDay: null,
                    userMode: 'NEW'
                }, {
                    label: '其他用户', value: 'ANOTHER',
                }]
            })
        }
    }

    render() {
        const { salesPromotionConfig, switchValue, loading, switchLoading, visible, withdrawalServiceFeeFake, withdrawalServiceFee } = this.state
        return (
            <div style={{ marginTop: '20px' }}>
                <Space size={20}>
                    <strong>礼物提现服务费促销</strong>
                    <Switch
                        checked={switchValue}
                        onChange={(e) => this.switchChange(e)} loading={switchLoading}
                    />
                </Space>
                <br />
                {
                    switchValue && <>
                        <div style={{ marginTop: '10px' }}>
                            {
                                salesPromotionConfig.pickType == 'ALL' ? <div>所有人，优惠后的提现服务费为{salesPromotionConfig.priceRatioByAll / 100}%。活动促销文案：{salesPromotionConfig.promotionOfficialByAll}</div>
                                    : salesPromotionConfig.pickType == 'NEW' ? <div>{salesPromotionConfig.definitionPickByNew == 1 ? `新用户注册${salesPromotionConfig.registerDaysByNew}天内` : `新用户前${salesPromotionConfig.limitNumberByNew}次礼物收益提现`}，优惠后的提现服务费为{salesPromotionConfig.priceRatioByNew / 100}%。活动促销文案：{salesPromotionConfig.promotionOfficialByNew}</div> : <>
                                        <div>{salesPromotionConfig.definitionPickByNew == 1 ? `新用户注册${salesPromotionConfig.registerDaysByNew}天内` : `新用户前${salesPromotionConfig.limitNumberByNew}次礼物收益提现`}，优惠后的提现服务费为{salesPromotionConfig.priceRatioByNew / 100}%。活动促销文案：{salesPromotionConfig.promotionOfficialByNew}</div>
                                        <div>其他用户，优惠后的提现服务费 {salesPromotionConfig.priceRatioByAnother / 100}%。活动促销文案：{salesPromotionConfig.promotionOfficialByAnother}</div>
                                    </>
                            }


                        </div>
                        <div style={{ marginTop: '20px', marginLeft: '200px' }}>
                            <TheButton
                                size="large"
                                type="primary"
                                haspermi={["wallet:salesPromotion:edit"]}
                                onClick={() => this.openModal()}
                            >
                                编辑
                            </TheButton>
                        </div>
                    </>
                }

                <Modal
                    width={1000}
                    visible={visible}
                    title={"礼物提现服务费促销活动"}
                    maskClosable={false}
                    onCancel={() => this.closeModal()}
                    onOk={() => this.onFinish()}
                    confirmLoading={loading}
                >
                    <p style={{ color: 'red' }}>当前：提现服务费为：{withdrawalServiceFee}%，提现服务费（划线）为：{withdrawalServiceFeeFake}%</p>
                    <Form
                        ref={this.formRef}
                        preserve={false}
                        labelCol={{
                            span: 3,
                        }}
                        wrapperCol={{
                            span: 16
                        }}
                        onValuesChange={this.onValuesChange}
                        initialValues={{
                            userRange: 'ALL',
                            sights: [{
                                label: '新用户', value: 'NEW',
                                userMode: ['NEW']
                            }, {
                                label: '其他用户', value: 'ANOTHER'
                            }]
                        }}
                    >
                        <Form.Item
                            name="userRange"
                            label="用户范围"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择指定用户'
                                },
                            ]}
                        >
                            <Select placeholder="请选择用户范围" style={{ width: 180 }}>
                                <Select.Option value="ALL">所有人</Select.Option>
                                <Select.Option value="NOALL">指定用户</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item

                            noStyle
                            shouldUpdate
                        >
                            {({ getFieldValue, setFieldsValue
                                , ...aaaa }) => {
                                const sights = getFieldValue('sights')
                                const userRange = getFieldValue('userRange')
                                // userRange !== 'ALL'&& resetFields(['sights'])
                                return userRange === 'ALL' ? <div style={{ paddingLeft: 90 }}>{this.getServicePriceAndTip(5)}</div> : <div style={{ paddingLeft: 90 }}>
                                    <Form.List style={{ marginBottom: 20 }} name="sights" required initialValue={[{
                                        userMode: '',
                                        definition: "",
                                        registerDay: '',
                                        payoutCount: '',
                                    }]}>
                                        {(fields, { }, { errors }) => {

                                            return fields.map((field, index) => {
                                                const key = sights[index].value
                                                return <>
                                                    <Form.Item

                                                        {...field}
                                                        name={[field.name, 'userMode']}
                                                        fieldKey={[field.fieldKey, 'userMode']}
                                                        key={field.key}
                                                    >
                                                        <Checkbox.Group >
                                                            <Checkbox disabled={key == 'NEW'} value={sights[index].value}>{sights[index].label}
                                                                {
                                                                    key == 'NEW' && sights[index].userMode == 'NEW' && <>
                                                                        <Form.Item
                                                                            {...field}
                                                                            style={{ paddingLeft: 40 }}
                                                                            name={[field.name, 'definition']}
                                                                            fieldKey={[field.fieldKey, 'definition']}
                                                                            rules={[{
                                                                                required: true,
                                                                                message: '请选择新用户定义'
                                                                            }]}
                                                                        >
                                                                            <Radio.Group>
                                                                                <Radio value={1}>
                                                                                    <Form.Item name={[field.name, 'registerDay']}
                                                                                        fieldKey={[field.fieldKey, 'registerDay']} rules={[
                                                                                            {
                                                                                                required: sights[index].definition == 1,
                                                                                                message: '请输入1~999范围内的整数'
                                                                                            },
                                                                                            {
                                                                                                message: '请输入1~999范围内的整数！',
                                                                                                min: 1,
                                                                                                max: 999,
                                                                                                type: 'number'
                                                                                            }
                                                                                        ]}>
                                                                                        <InputNumber min={1} max={999} precision={0} placeholder='请输入' addonBefore="定义1：注册" addonAfter="天内"></InputNumber>
                                                                                    </Form.Item>
                                                                                </Radio>
                                                                                <br></br>
                                                                                <Radio value={2}>
                                                                                    <Form.Item name={[field.name, 'payoutCount']}
                                                                                        fieldKey={[field.fieldKey, 'payoutCount']} rules={[
                                                                                            {
                                                                                                required: sights[index].definition == 2,
                                                                                                message: '请输入1~999范围内的整数'
                                                                                            }, {
                                                                                                message: '请输入1~999范围内的整数！',
                                                                                                min: 1,
                                                                                                max: 999,
                                                                                                type: 'number'
                                                                                            }
                                                                                        ]}>
                                                                                        <InputNumber min={1} max={999} precision={0} placeholder='请输入' addonBefore="定义2：前" addonAfter="次礼物收益提现"></InputNumber>
                                                                                    </Form.Item></Radio>
                                                                            </Radio.Group>
                                                                        </Form.Item>
                                                                        <div style={{ paddingLeft: 40 }}>
                                                                            {this.getServicePriceAndTip(12, field)}
                                                                        </div>
                                                                    </>
                                                                }
                                                                {
                                                                    key == 'ANOTHER' && sights[index].userMode == 'ANOTHER' && <>  {this.getServicePriceAndTip(12, field)} </>
                                                                }



                                                            </Checkbox>
                                                        </Checkbox.Group>
                                                    </Form.Item>


                                                </>
                                            })
                                        }}

                                    </Form.List>
                                </div>
                            }}
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        );
    }
}

export default SalesPromotion;
